% CALCULATE ERRORS AND VELOCITIES (not incl grand average velocity)
% for slow speed data (18 deg/s)

ylimit = [0 250];

for t = 1:numel(files)
    
    % Calculate errors
    trialsummary(1,t).error = target18.X(1:3*msPerCycle,1) - ...
        trialsummary(1,t).data.X(1:3*msPerCycle,1);
    
    % Calculate squared errors
    trialsummary(1,t).errsq = (trialsummary(1,t).error).^2;
    
    % Calculate RMS error
    trialsummary(1,t).RMSE = sqrt(nanmean(trialsummary(1,t).errsq));
    
    % List squared errors when behind or outside occluder for each speed
    trialsummary(1,t).errsqocc = trialsummary(1,t).errsq...
        (target18.occluder(1:3*msPerCycle,1));
    trialsummary(1,t).errsqfix = trialsummary(1,t).errsq...
        (~target18.occluder(1:3*msPerCycle,1));
    
    % Calculate RMS error behind occluders only
    trialsummary(1,t).RMSEocc = sqrt(nanmean(trialsummary(1,t).errsqocc));
    
    % Calculate RMS error outside occluders only
    trialsummary(1,t).RMSEfix = sqrt(nanmean(trialsummary(1,t).errsqfix));
    
    % Calculate velocity
    trialsummary(1,t).data.vel = ...
        velocity(trialsummary(1,t).data.X,smvp,scnw,scnwcm,view_dist);
    
    % Remove saccades from velocity data
    for i = 1: size(trialsummary(1,t).data.X, 1)
        %         if trialsummary(1,t).data.sac(i,1) == 1
        %             trialsummary(1,t).data.vel(i,1) = NaN;
        %         end
        if abs(trialsummary(1,t).data.vel(i,1)) > sacvel
            trialsummary(1,t).data.vel(i,1) = NaN;
        end
    end
end

% SORT RMSE INTO SPEEDS AND NOISE LEVELS AND PLOT
fn = 0;
fs = 0;
sn = 0;
ss = 0;
for t = 1:numel(files)
    if trialsummary(1,t).stimulus.smooth == 0
        SlowNoisy.RMSEs.no(sn+1) = trialsummary(1,t).RMSE;
        SlowNoisy.RMSEs.t(sn+1) = t;
        sn = sn + 1;
    else
        SlowSmooth.RMSEs.no(ss+1) = trialsummary(1,t).RMSE;
        SlowSmooth.RMSEs.t(ss+1) = t;
        ss = ss + 1;
    end
end

figure(2)
ax(1) = subplot(1,2,1);
bar(SlowNoisy.RMSEs.no)
set(gca,'XTickLabel',SlowNoisy.RMSEs.t)
xlabel('Trial');
ylabel('RMS error');
ylim(ylimit);
title('RMSE for 18 deg/s Noisy trials')

ax(2) = subplot(1,2,2);
bar(SlowSmooth.RMSEs.no, 'r')
set(gca,'XTickLabel',SlowSmooth.RMSEs.t)
xlabel('Trial');
ylabel('RMS error');
ylim(ylimit);
title('RMSE for 18 deg/s Smooth trials')

try
    suplabel(subject,'t')
catch
    disp('no suplabel function')
end

% maxRMSE = max(max(FastNoisy.RMSEs),max(FastSmooth.RMSEs),...
%     max(SlowNoisy.RMSEs),max(SlowSmooth.RMSEs));
% linkaxes(ax,'y');
% set(ax,'ylimmode','auto');